package com.woniuxy.cloud.usermultiassembly.web;


import com.woniuxy.cloud.UserAPI;
import com.woniuxy.cloud.form.UserForm;
import com.woniuxy.cloud.ticket52.common.result.Result;
import com.woniuxy.cloud.usermultiassembly.JWTHelper;
import io.jsonwebtoken.JwtHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class UserController implements UserAPI {

    @Autowired
    private JWTHelper jwtHelper;

    @Override
    public Result login(String username, String password) {
        if(username.equals("zhangsan")){
            //成功
            Map<String,Object> payload = new HashMap<>();
            Double randomValue = Math.floor(Math.random() * 1000);
            payload.put("userId", randomValue.intValue());
            String jwt = jwtHelper.createJWT(DateUtils.addDays(new Date(), 1), payload);
            return Result.success(jwt);
        }

        return Result.fail("失败");
    }

    public Result checkBalance(int userId, double amount){
        log.info("{},{}",userId,amount);
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String userId1 = request.getHeader("userId");
        log.info("从header获取到userId:{}",userId1);
        return Result.success();
    }

    public Result register(UserForm form,String from){
        log.info("注册{} ,来源{}",form,from);

        return Result.success();
    }


    public Result modifyPassword(int userId, String password){
        log.info("修改密码{}:{}",userId,password);

        return Result.success();
    }

    public Result getUserInfo(int userId){
        log.info("获取个人信息{}",userId);

        return Result.success();
    }
}
